package com.fanh.service.impl;

 import com.fanh.common.exception.Asserts;
 import com.fanh.common.util.CommonUtil;
 import com.fanh.dao.GuideCourseDao;
 import com.fanh.dto.GuideCourseResult;
 import com.fanh.mapper.GuideCourseMapper;
 import com.fanh.mapper.GuidePayMapper;
 import com.fanh.model.GuideCourse;
 import com.fanh.model.GuidePay;
 import com.fanh.model.GuidePayExample;
 import com.fanh.service.GuidePayService;
 import com.github.pagehelper.PageHelper;
 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;

 import java.math.BigDecimal;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.List;


@Service("guidePayService")
public class GuidePayServiceImpl implements GuidePayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GuidePayServiceImpl.class);
    @Autowired
    private GuidePayMapper guidePayMapper;
    @Autowired
    private GuideCourseMapper guideCourseMapper;
    @Autowired
    private GuideCourseDao guideCourseDao;

    @Override
    public List<GuidePay> GuidePayList(String userId, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        GuidePayExample example = new GuidePayExample();
        example.createCriteria().andUserIdEqualTo(userId);
        return guidePayMapper.selectByExample(example);
    }

    @Override
    public int freeSubject(String userId, String courseId) {
        GuideCourse course =guideCourseMapper.selectByPrimaryKey(courseId);
        if(course.getFree() == 0) {
            Asserts.fail("课程不能免费订阅");
         }

        GuidePay guidePay = new GuidePay();
        guidePay.setId(CommonUtil.uuid());
        guidePay.setType("2");
        guidePay.setTimeScope("3");
        guidePay.setMethod("3");
        guidePay.setAccount("");
        guidePay.setCoin(new BigDecimal(0));
        guidePay.setPrice(new BigDecimal(0));
        guidePay.setCourseId(courseId);
        guidePay.setUserId(userId);
        guidePay.setStatus("1");
        guidePay.setAccount("");
        guidePay.setStartDate(new Date());
        guidePay.setPayTime(new Date());
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, 20);
        guidePay.setEndDate(cal.getTime());

        return guidePayMapper.insertSelective(guidePay);
    }

    @Override
    public List<GuideCourseResult> payCourseReading(String userId, Integer type, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        List<GuideCourseResult>  list = guideCourseDao.guideCourseReading(userId,Integer.toString(type) );
        return list;
    }
}
